# 导入json
import json
from flask import request
# .. 上一级的__init__.py 文件
from .. import db
from ..base import base
# 从models中导入TbWorker类
from ..models import TbWorker

# 引入websock
from .. import socketio
# 导入随机数
import random




# http://localhost/base/build/worker/page?area=%E6%96%B0%E5%8D%8E%E5%8C%BA&name=aa&contact=bb&phone=cc
@base.route('/build/worker/list', methods=['GET'])
def TbWorker_list():
    construction_id = request.args.get("construction_id")
    area = request.args.get("area")
    name = request.args.get("name")
    address = request.args.get("address")
    phone = request.args.get("phone")
    face_img = request.args.get("face_img")
    face_features = request.args.get("face_features")
    # 查询的列表
    filters = []
    # '' none
    if name:
        filters.append(TbWorker.name.like('%' + name + '%'))
    if area:
        filters.append(TbWorker.area.like('%' + area + '%'))
    if address:
        filters.append(TbWorker.address.like('%' + address + '%'))
    if construction_id:
        filters.append(TbWorker.construction_id == construction_id)
    # 从第pageNum页开始，每页显示pageSize条
    pageNum = request.args.get("pageNum", default=1, type=int)
    pageSize = request.args.get("pageSize", default=10, type=int)
    # 返回分页的对象
    pagination = TbWorker.query.filter(*filters).paginate(page=pageNum, per_page=pageSize, error_out=False)
    # 查询5的数据
    ite = pagination.items
    # 所有的数据
    total = pagination.total
    # return json.dumps([i.to_dict() for i in ite],ensure_ascii=False)
    return json.dumps({'total': total, 'data': [i.to_dict() for i in ite]}, ensure_ascii=False)


@base.route('/build/worker', methods=['POST'])
def TbWorker_save():
    name = request.json.get("name")
    area = request.json.get("area")
    address = request.json.get("address")
    phone = request.json.get("phone")
    construction_id = request.json.get("construction_id")
    face_img = request.json.get("face_img")
    face_features = request.json.get("face_features")
    #     创建对象
    tb = TbWorker(name=name, area=area, address=address, phone=phone, construction_id=construction_id,
                  face_img=face_img, face_features=face_features)
    db.session.add(tb)
    db.session.commit()
    return json.dumps({'code': 0, 'msg': '添加成功'})


@base.route('/build/worker', methods=['PUT'])
def TbWorker_update():
    # 获取id
    id = request.json.get("id")
    name = request.json.get("name")
    area = request.json.get("area")
    address = request.json.get("address")
    phone = request.json.get("phone")
    construction_id = request.json.get("construction_id")
    face_img = request.json.get("face_img")
    face_features = request.json.get("face_features")
    #     根据id获取查询对象
    tb = TbWorker.query.get(id)
    # 跟新数据
    if name:
        tb.name = name
    if area:
        tb.area = area
    if address:
        tb.address = address
    if phone:
        tb.phone = phone
    if construction_id:
        tb.construction_id = construction_id
    if face_img:
        tb.face_img = face_img
    if face_features:
        tb.face_features = face_features
    # 提交数据
    db.session.commit()
    return json.dumps({'code': 0, 'msg': '更新成功'})


# 路径传参 /build/worker/2
@base.route('/build/worker/<id>', methods=['DELETE'])
def TbWorker_delete(id):
    # 查询需要删除的对象
    tb = TbWorker.query.get(id)
    db.session.delete(tb)
    # 提交数据
    db.session.commit()
    return json.dumps({'code': 0, 'msg': '删除成功'})

@base.route('/build/worker/test', methods=['GET'])
def TbWorker_test():
    # 后端触发的事件是'my_response'
    ll = [random.randint(0, 200) for i in range(7)]

    l2 = [random.randint(0, 200) for i in range(7)]
    # 传输的数据必须是序列化, str 是序列化好的
    # 把数据序列化,转化成json 类型的字符串
    socketio.emit('my_response', json.dumps(ll) ,namespace='/test')
    return "测试完美成功"


@socketio.on('connect', namespace='/test')
def socketio_connected():
    print('服务器已经连接')

# 断开自动执行
@socketio.on('disconnect', namespace='/test')
def socketio_disconnect():
    print('服务器已经断开')




@base.route('/build/worker/<id>', methods=['GET'])
def TbWorker_getByID(id):
    # 查询需要删除的对象
    tb = TbWorker.query.get(id)
    return json.dumps({'code': 0, 'msg': '删除成功', 'data': tb.to_dict()})



